{% extends "base.html" %}

{% block media %}
    <style>
        #totp-or-scratch-code-container {
            margin: 0.5em 0;
        }

        #id_totp_token {
            width: 100%;
        }

        .totp-or-scratch-code-panel-message {
            width: 300px;
        }
    </style>
{% endblock %}

{% block js_media %}
    <script>
        // This is basically impossible to write without ES6, hence separate script block.
        $(() => {
            {% include "user/webauthn-helpers.js" %}

            function buf2hex(buffer) {
                return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
            }

            $('#use-webauthn').click(event => {
                event.preventDefault();

                if (typeof window.PublicKeyCredential === 'undefined') {
                    alert('{{ _('WebAuthn is not supported by your browser.') }}');
                    return;
                }

                $.getJSON('{{ url('webauthn_assert') }}')
                    .done(publicKey => {
                        decodeJSONBytes(publicKey);
                        navigator.credentials.get({publicKey})
                            .then(credential => {
                                credential = {
                                    id: credential.id,
                                    response: {
                                        authData: urlSafeBase64Encode(credential.response.authenticatorData),
                                        clientData: urlSafeBase64Encode(credential.response.clientDataJSON),
                                        signature: buf2hex(credential.response.signature),
                                    }
                                };
                                $('#id_webauthn_response').val(JSON.stringify(credential));
                                $('#2fa-form').submit();
                            });
                    })
                    .fail(() => alert('{{ _('Failed to contact server.') }}'));
            })
        });
    </script>
{% endblock %}

{% block body %}
    <div class="auth-flow-form">
        <form action="" method="post" class="form-area" id="2fa-form">
            {% csrf_token %}
            {% if form.errors %}
                <div id="form-errors">
                    <p class="error">
                        {%- if form.errors['totp_token'] -%}
                            {{ ' '.join(form.errors['totp_token']) }}
                        {%- else -%}
                            {{ ' '.join(form.non_field_errors()) }}
                        {%- endif -%}
                    </p>
                </div>
            {% endif %}

            {% if request.profile.is_totp_enabled or request.profile.scratch_codes %}
                <div class="totp-or-scratch-code-panel-message"><label class="inline-header grayed">
                    {% if request.profile.is_totp_enabled %}
                        {{ _('Enter the 6-digit code generated by your app or one of your 16-character scratch codes:') }}
                    {% else %}
                        {{ _('Enter one of your 16-character scratch codes:') }}
                    {% endif %}
                </label></div>
                <div id="totp-or-scratch-code-container"><span class="fullwidth">{{ form.totp_or_scratch_code }}</span></div>
                <hr>
            {% endif %}
            {% if request.profile.is_webauthn_enabled %}
                {{ form.webauthn_response }}
                <button style="display: inline" id="use-webauthn" type="button">{{ _('Use security key') }}</button>
            {% endif %}
            {% if request.profile.is_totp_enabled %}
                <button style="float:right;" type="submit">{{ _('Login!') }}</button>
            {% elif request.profile.scratch_codes %}
                <button style="float:right;" type="submit">{{ _('Use scratch code') }}</button>
            {% endif %}
        </form>
        {% if not is_hardcore %}
            <p class="totp-or-scratch-code-panel-message">{{ _('If you lost your authentication device and are unable to use your scratch codes, please contact us at %(email)s.', email=SITE_ADMIN_EMAIL)|urlize }}</p>
        {% endif %}
    </div>
{% endblock %}
